package com.example.abc.websocket;

import com.example.abc.dto.MyUserDetails;
import com.example.abc.web.IndexController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.web.socket.WebSocketSession;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Peter on 2018/5/8.
 * 持有所有的websocket在线用户
 */
public class OnlineUsers {
    public static final Logger logger = LoggerFactory.getLogger(OnlineUsers.class);
    private static final Map<String, WebSocketSession> users = new ConcurrentHashMap<>();

    public static WebSocketSession getUser(String uid) {
        return users.get(uid);
    }

    public static void addUser(WebSocketSession session) {
        users.put(getUid(session), session);
        logger.info("Add WebSocket User. Now Users Size is " + users.size());
    }

    public static void removeUser(WebSocketSession session) {
        users.remove(getUid(session));
        logger.info("Remove WebSocket User. Now Users Size is " + users.size());
    }

    private static String getUid(WebSocketSession session){
        Principal principal =session.getPrincipal();
        Authentication auth = (Authentication)principal;
        MyUserDetails userDetails = (MyUserDetails)auth.getPrincipal();
        return userDetails.getUid();
    }

}
